import fly from 'flyio'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import qs from 'qs'

// 实例级配置
fly.config.timeout = 5e3
fly.config.baseURL = process.env.BASE_API

// 添加拦截器
fly.interceptors.request.use((config, promise) => {
  // 给所有请求添加自定义header
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  if (store.getters.token) {
    config.headers['Authorization'] = store.getters.token
  }
  if (config.method === 'post') {
    config.data = qs.stringify({
      ...config.data
    })
  }
  return config
})

// 添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  response => {
    // 只将请求结果的data字段返回
    return response.data
  },
  error => {
    if (error.message.includes('timeout')) {
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.message.includes('502')) {
      location.reload()
    } else if (error.message.includes('500')) {
      Message({
        message: '服务器开了一会小差',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    store.commit('HIDE_LOADING')
    return Promise.reject(error)
  }
)

export default fly
